import {fuzzyQuery, getConfig, insertOne, queryOne, selectAll, setConfig} from "./fake-db"
import createHandler from "./request"
import {now} from "../utils/time"
import {v4} from "uuid"

function countRoles(roles) {
    roles = JSON.parse(JSON.stringify(roles))
    const users = selectAll('user')
    const counter = {}
    for (let user of users) {
        if (!counter[user.role]) {
            counter[user.role] = 1
        } else {
            counter[user.role] += 1
        }
    }
    for (let role of roles) {
        const count = counter[role.id]
        role.count = count ? count : 0
    }
    return roles
}

const getAllRole = createHandler((count = false) => {
    const roles = selectAll('role')
    return {
        code: 0,
        data: count ? countRoles(roles) : roles
    }
})

const queryRole = createHandler(name => {
    const roles = fuzzyQuery('role', 'name', name)
    return {
        code: 0,
        data: countRoles(roles)
    }
})

const deleteRole = createHandler(name => {
    const roles = selectAll('role')
    const index = roles.findIndex(role => role.name === name)
    if (index !== -1) {
        roles.splice(index, 1)
    }
    return {
        code: 0
    }
})

const setRoleEnable = createHandler((name, enable) => {
    const role = queryOne('role', 'name', name)
    if (!role) return {
        code: 3001,
        msg: '角色不存在'
    }
    role.enable = enable
    return {
        code: 0
    }
})

const changeRole = createHandler((oldName, newName, describe) => {
    const role = queryOne('role', 'name', oldName)
    if (!role) return {
        code: 3001,
        msg: '角色不存在'
    }
    if (oldName !== newName && queryOne('role', 'name', newName)) return {
        code: 3002,
        msg: '角色名称重复'
    }

    role.name = newName
    role.describe = describe
    return {
        code: 0
    }
})

const createRole = createHandler((name, describe) => {
    if (queryOne('role', 'name', name)) return {
        code: 3002,
        msg: '角色名称重复'
    }
    const role = {
        id: v4(),
        name,
        describe,
        created_at: now(),
        enable: true
    }
    insertOne('role', role)
    return {
        code: 0
    }
})

const getDefaultRole = createHandler(() => ({
    code: 0,
    data: getConfig('defaultRole')
}))

const setDefaultRole = createHandler((role) => {
    setConfig('defaultRole', role)
    return {
        code: 0
    }
})

export {getAllRole, queryRole, deleteRole, setRoleEnable, changeRole, createRole, getDefaultRole, setDefaultRole}